﻿# -*-coding:utf-8-*-
import os
import subprocess
import sys
# import win32api
import tempfile
# import importlib
# importlib.reload(sys)
# import codecs
# sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach())
#
try:
    import nuke
    reload(sys)
    sys.setdefaultencoding('utf8')
except Exception as reload_ERR:
    print('Testing')
import time
import datetime
import json
import socket
import shutil
from submitDeadline import DeadlineWindow
# import threading
# import win32file


if sys.version>'3':
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    from PySide2.QtWidgets import *
else:
    from PySide2.QtGui import *
    from PySide2.QtCore import *
    from PySide2.QtWidgets import *



class WriteNodeList(QListWidget):

    nodename_Signal=Signal(str)
    def __init__(self):
        super(WriteNodeList, self).__init__()

        self.setWindowTitle(u'双击选择')
        self.doubleClicked.connect(self._choose_write)

    def _choose_write(self,index):
        item=self.itemFromIndex(index)
        text=item.text()
        self.nodename_Signal.emit(text)
        self.close()

    def init_items(self,write_list):
        if write_list:
            self.clear()
            for i in write_list:
                item=QListWidgetItem()
                item.setText(i.name())
                item.setTextAlignment(Qt.AlignCenter)
                self.addItem(item)



class Name(QWidget):

    name_Signal = Signal(str)

    def __init__(self):
        super(Name, self).__init__()
        self.main_layout = QVBoxLayout()
        self.name_label = QLabel('New Name:')
        self.name_edit = QLineEdit()
        self.name_btn = QPushButton('OK')
        self.name_btn.clicked.connect(self._set_name)
        self.main_layout.addWidget(self.name_label)
        self.main_layout.addWidget(self.name_edit)
        self.main_layout.addWidget(self.name_btn)
        self.setLayout(self.main_layout)

    def _set_name(self):
        name = self.name_edit.text()
        if name:
            self.name_Signal.emit(name)
            self.close()

class ListModel(QListWidget):
    data_Signal = Signal(dict)

    def __init__(self):
        super(ListModel, self).__init__()
        # self.clicked.connect(self._show_info)
        self.doubleClicked.connect(self._show_info)
        self.data = {}
    def set_data(self,data):
        """
        :param data:
        :return:
        """
        if data:
            #print('set_data:',data)#{'LL01_01_004': {'description': '', 'entity_name': 'LL01_01_004', 'img_path': 'path', 'frame': '15', 'resolution': None}, 'LL01_01_001a':
            self.clear()
            self.data = data
            for k, v in data.items():
                item = QListWidgetItem()
                item.setText(k)
                item.setTextAlignment(Qt.AlignCenter)
                self.addItem(item)
            self.sortItems()

    def _show_info(self,index):
        item = self.itemFromIndex(index)
        text = item.text()
        self.data_Signal.emit(self.data[text])
        # print('_show_info:',self.data[text])
        self.close()

    def filter_item(self,text):
        try:
            # item_list=[]
            for i in range(self.count()):
                item=self.item(i)
                project_name=item.text()
                if text not in project_name:
                    item.setHidden(True)
        except Exception as filter_item_ERR:
            print(str(filter_item_ERR))

    def add_asset(self,asset_name):
        item=QListWidgetItem()
        item.setText(asset_name)
        item.setTextAlignment(Qt.AlignCenter)
        self.addItem(item)

    def show_all(self):
        for i in range(self.count()):
            item = self.item(i)
            item.setHidden(False)

class ListModel2(QListWidget):
    data_Signal = Signal(str)

    def __init__(self):
        super(ListModel2, self).__init__()
        self.doubleClicked.connect(self._show_info)

    def set_list(self,data_list):
        """
        :param data:
        :return:
        """
        self.clear()
        if data_list:
            asset_item = QListWidgetItem()
            asset_item.setText('Asset')
            asset_item.setTextAlignment(Qt.AlignCenter)
            self.addItem(asset_item)
            # self.data = data
            for data in data_list:
                item = QListWidgetItem()
                item.setText(data)
                item.setTextAlignment(Qt.AlignCenter)
                self.addItem(item)
            self.sortItems()

    def _show_info(self,index):
        item = self.itemFromIndex(index)
        text = item.text()
        self.data_Signal.emit(text)
        # print('_show_info:',self.data[text])
        self.close()

    def filter_item(self,text):
        try:
            # item_list=[]
            for i in range(self.count()):
                item = self.item(i)
                project_name = item.text()
                if text not in project_name:
                    item.setHidden(True)
        except Exception as filter_item_ERR:
            print(str(filter_item_ERR))


    def show_all(self):
        for i in range(self.count()):
            item = self.item(i)
            item.setHidden(False)

class ShotListWindow(QDialog):
    shot_Signal = Signal(dict)

    def __init__(self):
        super(ShotListWindow, self).__init__()
        self.btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.setWindowTitle('Shots')
        self.main_layout = QVBoxLayout()
        self.search_layout = QHBoxLayout()
        self.search_edit = QLineEdit()
        self.search_edit.textEdited.connect(self._text_edited)
        self.search_btn = QPushButton('search')
        self.search_btn.clicked.connect(self._filter_shot)
        self.search_btn.setStyleSheet(self.btn_style)
        self.add_btn = QPushButton('create')
        self.add_btn.clicked.connect(self._add_asset)
        self.add_btn.setStyleSheet(self.btn_style)
        self.search_layout.addWidget(self.search_edit)
        self.search_layout.addWidget(self.search_btn)
        self.search_layout.addWidget(self.add_btn)
        self.shot_list = ListModel()
        self.shot_list.data_Signal.connect(self._get_shot)
        self.main_layout.addLayout(self.search_layout)
        self.main_layout.addWidget(self.shot_list)
        self.setLayout(self.main_layout)

    def set_data(self,data):
        if data:
            self.shot_list.set_data(data)

    def _filter_shot(self):
        """
        filter shot
        :return:
        """
        text = self.search_edit.text()
        if text:
            self.shot_list.filter_item(text)

    def _add_asset(self):
        text = self.search_edit.text()
        if text:
            self.shot_list.add_asset(text)

    def _text_edited(self, ha):
        if not ha:  # ��û����������ʱ��������
            # self.create_items(self.data_list)
            self.shot_list.show_all()

    def _get_shot(self,data):
        self.shot_Signal.emit(data)
        self.close()

class EpsListWindow(QDialog):
    eps_Signal = Signal(str)

    def __init__(self):
        super(EpsListWindow, self).__init__()
        self.btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.setWindowTitle('Eps')
        self.main_layout = QVBoxLayout()
        self.search_layout = QHBoxLayout()
        self.search_edit = QLineEdit()
        self.search_edit.textEdited.connect(self._text_edited)
        self.search_btn = QPushButton('search')
        self.search_btn.clicked.connect(self._filter_shot)
        self.search_btn.setStyleSheet(self.btn_style)
        self.search_layout.addWidget(self.search_edit)
        self.search_layout.addWidget(self.search_btn)
        self.eps_list = ListModel2()
        self.eps_list.data_Signal.connect(self._get_eps)
        self.main_layout.addLayout(self.search_layout)
        self.main_layout.addWidget(self.eps_list)
        self.setLayout(self.main_layout)

    def set_list(self,eps_list):
        self.eps_list.clear()
        if eps_list:
            # print('eps set_data:',data)
            self.eps_list.set_list(eps_list)

    def _filter_shot(self):
        """
        filter shot
        :return:
        """
        text = self.search_edit.text()
        if text:
            self.eps_list.filter_item(text)


    def _text_edited(self, ha):
        if not ha:  #
            self.eps_list.show_all()

    def _get_eps(self,data):
        self.eps_Signal.emit(data)
        self.close()


class FileListMode(QListWidget):

    path_Signal=Signal(str)
    def __init__(self):
        super(FileListMode, self).__init__()
        self.clicked.connect(self._select_path)
        self.data={}  # {'file_dir_name':path,}

    def set_data(self,data):
        if data:
            self.clear()
            self.data=data
            for k,v in data.items():
                item=QListWidgetItem()
                item.setText(k)
                self.addItem(item)
            self.sortItems()

    def _select_path(self,index):
        # print(index)
        item=self.itemFromIndex(index)
        file_name=item.text()
        path=self.data[file_name]
        self.path_Signal.emit(path)

class MZProgresBar(QWidget):
    force_close_Signal =  Signal(int)
    def __init__(self):#,nk_name
        super(MZProgresBar, self).__init__()
        # self.path=nk_name
        self.main_layout=QVBoxLayout()
        self.main_layout.setSpacing(0)
        label_font=QFont('',12)
        self.show_label=QLabel(u'正在打包...')
        # self.show_label.setFont(label_font)
        # self.show_label.setStyleSheet('color: #d9d9d9')
        self.progress_layout=QHBoxLayout()
        self.progress=QProgressBar()
        self.progress.setMaximumHeight(15)
        self.percen_label=QLabel('0')
        self.percen_label.setStyleSheet('color: #d9d9d9')
        self.percen_label.setFont(label_font)
        self.progress_layout.addWidget(self.progress)
        self.progress_layout.addWidget(self.percen_label)
        self.main_layout.addWidget(self.show_label)
        self.main_layout.addLayout(self.progress_layout)
        self.setLayout(self.main_layout)

    def set_percent(self,percent):
        self.progress.setValue(percent)
        self.percen_label.setText(str(percent))

    def closeEvent(self, *args, **kwargs):
        print(u'关闭进度')
        self.force_close_Signal.emit(1)
        self.close()


class CopyThread(QThread):

    def __init__(self,copy_paths,parent):
        super(CopyThread, self).__init__()
        self.copy_paths = copy_paths
        self.parent = parent
        # self.discopys = parent.discopys

    # def run(self):
    #     for path in self.copy_paths:
    #         src_path,tar_path = path
    #         # shutil.copyfile(src_path, tar_path)
    #         src_path = src_path.replace('/', '\\')
    #         tar_path = tar_path.replace('/', '\\')
    #         out_temp = tempfile.SpooledTemporaryFile(bufsize=100 * 1000)
    #         fileno = out_temp.fileno()
    #         time.sleep(0.1)
    #         try:
    #             cmd = 'copy {} {}'.format(src_path, tar_path)
    #             res = subprocess.Popen(cmd, shell=True, stdout=fileno,
    #                                    stderr=fileno)
    #             res.wait()
    #             out_temp.seek(0)
    #             lines = out_temp.readlines()
    #             self.parent.count += 1
    #
    #             # print('end copy',tar_path)
    #         except Exception as copyERR:
    #             # print('copyERR:',src_path)
    #             pass
    #             # self.discopys.append(src_path)
    #         finally:
    #             out_temp.close()

    def run(self):
        for path in self.copy_paths:
            src_path,tar_path = path
            # shutil.copyfile(src_path, tar_path)
            # src_path = src_path.replace('/', '\\')
            # tar_path = tar_path.replace('/', '\\')
            src_path = src_path.replace('\\', '/')
            # src_path = win32api.GetShortPathName(src_path)
            tar_path = tar_path.replace('\\', '/')
            _dir = os.path.dirname(tar_path)
            if not os.path.exists(_dir):
                os.makedirs(_dir)
            try:
                if not os.path.exists(tar_path):
                    shutil.copyfile(src_path,tar_path)
                self.parent.count += 1
            except Exception as copyERR:
                print('copyERR:',src_path)
                # print('copyERR:',copyERR,src_path)
            # finally:
            #     self.parent.count += 1



class ExportMov(QDialog):

    def __init__(self,parent=None):
        super(ExportMov, self).__init__(parent)
        self.HOST = '192.168.1.222'
        self.PORT = 4455  # 5566  #
        self.BUFFER = 20480  # 00
        self.cgtwpy_path = r'C:/CgTeamWork_v6/python/python.exe'

        self.dir_path = os.path.dirname(__file__)
        self.scripy_path = os.path.join(self.dir_path,'cgtw_scripts/ExternalSubmit.py').replace('\\','/')
        self.note_path = os.path.join(self.dir_path,'cgtw_scripts','ExternalNote.py').replace('\\','/')

        self.eps_list = []  # 当前项目下的所有集数
        # self.current_project = ''  # current selected project
        # self.current_eps = ''  # current selected eps
        self.current_artists = []  # 当前部门人员
        self.asset_data = {}  # 该人员的所有任务 {cg_id:data,cg_id:data,...}
        # self.current_shot = ''  # current selected shot
        self.current_asset = {}  #当前选择的资产信息{'entity_name': 'FNDH_efx_suiBoLi', 'description': '', 'cg_id': 'proj_fndh,asset,A650DCA7-8FDB-1E2B-E9C0-9B3F5175096A'}
        # self.current_pipeline = ''  # current selected pipeline
        self.daily_dir = r'\\192.168.1.248\3d\efx\dailies'
        self.daily_path = ''  # ʵʱ��������յ�daily���·��daily_path
        self.cgtw_path = ''
        self.write_data = {}  # {'Write1':write1Node,'Write2':write2Node,...}
        # self.current_nuke_path = ''  # ��ǰ�򿪵�nuke��ԭʼ·��������ύʱ���Ĵ�ֵ
        # self.save_path = ''  # ��nuke�ļ����յ����·�� //192.168.1.33/FX/Render/EC12-21-34/test.nk
        # self.nk_data = {}  # ��¼nuke����ԭʼ�����ж�Ӧ�ڵ��·����Ϣ{'project': nkname, 'data': data} eg:{'project':'FNDH','data':{'Read1':['Read','E:/AA.exr'],'vlt':['vfield_file','E:/vv/la.lvt']}} #ֻ��lut��·�����Ʋ�һ��
        self.current_write = None  # ��ǰѡ�е�Write�ڵ�
        # self.request_project_info = {}  # request project infomation data

        self.current_project_data = {}
        #current selected project info #{'database': 'proj_fndh', 'entity_name': 'FNDH', 'full_name': '�����ŭ�
        # ĺ�', 'eps_list': 'test|FNDH58|FNDH60|FNDH61|FNDH62|FNDH63|FNDH65|FNDH66|FNDH67|FNDH68|FNDH69|FNDH70
        #|FNDH72|FNDH73|FNDH75|FNDH76|FNDH78|FNDH83|FNDH84|FNDH85|FNDH88|FNDH89|FNDH90|FNDH91|FNDH92|FNDH93|FNDH94|
        # FNDH95|FNDH96|FNDH97|FNDH98|FNDH100|FNDH101|FNDH102|FNDH103|FNDH104|FNDH105|FNDH99|FNDH02', 'fps': '24'}
        self.current_project_config = {} #{'fps':'24','color': '#f6e7aa','resolution' :'3840x2160','path':'\\\\192.168.1.238\\cgteamwork5\\FNDH','full_name':'�����ŭ�ĺ�', 'entity_name':'FNDH'}
        self.current_shot_info = {}  # current shot info  #{'description': '���㣬�꣬���죬·����ʪ', 'entity_name': 'FNDH100_0020_01', 'img_path': '/upload/image/proj_fndh/min/51088c52f282cc9c971dd0bd767b300c.png', 'frame': '63'}
        self.task_data = {}  # {'efx':{'cg_id':cg_id,'task_name':efx},'efx_��������':{'cg_id':cg_id,'task_name':efx_��������}}
        self.pipeline_nas_map = {'FX_Previs': 'FX_Previs', 'FX': 'efx', 'FX_Cloth': 'cloth', 'FX_Crowd': 'crowd',
                                 'CFX': 'cfx', 'Environment': 'sce', 'Env_Postviz': 'env', 'Rig': 'Rig'}
        self.pipeline_map = {'FX_Previs': 'efx_previs', 'FX': 'efx', 'FX_Cloth': 'efx', 'FX_Crowd': 'efx', 'CFX': 'cfx','Environment': 'env', 'Env_Postviz': 'env', 'Rig': 'Rig'}
        self.btn_style = """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#A9A9A9}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""
        self.close_btn_style= """QPushButton{color:black}
                                  QPushButton:hover{color:red}
                                 QPushButton{background-color:#1C1C1C}
                                  QPushButton{border:2px}
                                  QPushButton{border-radius:3px}
                                  QPushButton{padding:1px 1px}"""

        rex = QRegExp("[0-9]+$")
        rv = QRegExpValidator(rex, self)

        self.mid_font = QFont('',11,65)

        self.setWindowTitle('ExportMov')
        self.main_layout = QVBoxLayout()
        self.main_layout.setSpacing(12)

        self.project_setting_label = QLabel(u'项目设置')
        self.project_setting_label.setAlignment(Qt.AlignCenter)
        self.project_setting_label.setFont(self.mid_font)
        self.project_layout = QHBoxLayout()
        self.project_label = QLabel('Project:')
        self.choose_project_btn = QPushButton('- -')
        self.choose_project_btn.setStyleSheet(self.btn_style)
        self.choose_project_btn.clicked.connect(self._open_project_window)
        self.project_layout.addWidget(self.project_label)
        self.project_layout.addWidget(self.choose_project_btn)
        self.eps_layout = QHBoxLayout()
        self.eps_label = QLabel('Eps:')
        # self.eps_comb = QComboBox()
        # self.eps_comb.currentTextChanged.connect(self._eps_changed)
        self.eps_btn = QPushButton('- -')
        self.eps_btn.setStyleSheet(self.btn_style)
        self.eps_btn.clicked.connect(self._open_eps_window)
        self.eps_layout.addWidget(self.eps_label)
        # self.eps_layout.addWidget(self.eps_comb)
        self.eps_layout.addWidget(self.eps_btn)
        self.artists_layout = QHBoxLayout()
        self.artists_label = QLabel('Artist(资产必选):')
        self.artists_label.setVisible(False)
        self.artists_comb = QComboBox()
        self.artists_comb.setVisible(False)
        self.artists_comb.currentTextChanged.connect(self._artist_changed)
        self.artists_layout.addWidget(self.artists_label)
        self.artists_layout.addWidget(self.artists_comb)

        self.shot_layout = QHBoxLayout()
        self.shot_label = QLabel('Shot:')
        self.shot_list_btn=QPushButton('- -')
        self.shot_list_btn.clicked.connect(self._open_shot_window)
        self.shot_list_btn.setStyleSheet(self.btn_style)
        self.shot_layout.addWidget(self.shot_label)
        self.shot_layout.addWidget(self.shot_list_btn)
        self.pipeline_layout = QHBoxLayout()
        self.pipeline_label = QLabel('Pipeline:')
        self.pipeline_comb = QComboBox()
        self.pipeline_layout.addWidget(self.pipeline_label)
        self.pipeline_layout.addWidget(self.pipeline_comb)
        self.init_pipeline_comb()
        self.pipeline_comb.currentTextChanged.connect(self._pipeline_changed)
        self.task_name_layout = QHBoxLayout()
        self.task_name_label = QLabel('Task Name:')
        self.task_name_comb = QComboBox()
        self.task_name_comb.currentTextChanged.connect(self._task_name_changed)
        self.task_name_comb.setMinimumWidth(300)
        self.task_name_layout.addWidget(self.task_name_label)
        self.task_name_layout.addWidget(self.task_name_comb)


        # self.mov_layout=QHBoxLayout()
        # self.mov_label=QLabel('mov:')
        # self.mov_list_comb=QComboBox()
        # self.mov_list_comb.setMinimumWidth(250)
        # self.mov_layout.addWidget(self.mov_label)
        # self.mov_layout.addWidget(self.mov_list_comb)


        # self.element_layout=QHBoxLayout()
        # self.element_label=QLabel('Element:')
        # self.element_edit=QLineEdit()
        # self.element_edit.setText('element')
        # self.element_layout.addWidget(self.element_label)
        # self.element_layout.addWidget(self.element_edit)

        self.artist_layout = QHBoxLayout()
        self.artist_label = QLabel(u'Artist:')
        self.artist_show = QLabel('xxx')
        self.artist_layout.addWidget(self.artist_label)
        self.artist_layout.addWidget(self.artist_show)

        self.fps_layout = QHBoxLayout()
        self.fps_layout.setAlignment(Qt.AlignLeft)
        self.fps_label = QLabel('FPS:')
        self.fps_edit = QLineEdit()
        self.fps_edit.setMaximumWidth(50)
        self.fps_layout.setContentsMargins(0, 0, 220, 0)
        self.fps_layout.addWidget(self.fps_label)
        self.fps_layout.addWidget(self.fps_edit)
        self.frame_layout = QHBoxLayout()
        self.frame_label = QLabel('Frame Range:')
        self.start_edit = QLineEdit()
        self.end_edit = QLineEdit()
        self.patch_project_btn=QPushButton(u'使用项目设置')
        self.patch_project_btn.clicked.connect(self._patch_project_setting)
        self.patch_project_btn.setStyleSheet(self.btn_style)
        self.frame_layout.addWidget(self.frame_label)
        self.frame_layout.addWidget(self.start_edit)
        self.frame_layout.addWidget(self.end_edit)
        self.frame_layout.addWidget(self.patch_project_btn)

        self.show_info_layout = QHBoxLayout()
        self.show_info_btn = QPushButton(u'显示镜头信息')
        self.show_info_btn.clicked.connect(self._show_shot_info)
        self.show_info_btn.setStyleSheet(self.btn_style)
        self.open_cgtw_dir_btn = QPushButton(u'打开cgtw目录')
        self.open_cgtw_dir_btn.clicked.connect(self._open_cgtw_render_dir)
        self.open_cgtw_dir_btn.setStyleSheet(self.btn_style)
        self.show_info_layout.addWidget(self.show_info_btn)
        self.show_info_layout.addWidget(self.open_cgtw_dir_btn)

        self.nuke_label = QLabel(u'Nuke 工程')
        self.nuke_label.setAlignment(Qt.AlignCenter)
        self.nuke_label.setFont(self.mid_font)

        self.version_layout = QHBoxLayout()
        self.version_layout.setAlignment(Qt.AlignLeft)
        self.version_label = QLabel(u'version  :  ')
        self.version_comb = QComboBox()
        self._init_version_comb()
        self.version_comb.currentTextChanged.connect(self._update_current_version)
        self.current_version_label = QLabel(u'当前工程版本为:xxx')
        self.version_layout.addWidget(self.version_label)
        self.version_layout.addWidget(self.version_comb)
        self.version_layout.addWidget(self.current_version_label)
        self._update_current_version()

        self.nuke_project_layout = QHBoxLayout()
        self.nuke_dir_label = QLabel('Nuke Direction :')
        self.nuke_dir_edit = QLineEdit()
        self._init_nuke_dir()
        self.nuke_dir_btn = QPushButton('...')
        self.nuke_dir_btn.clicked.connect(self._choose_nuke_dir)
        self.nuke_dir_btn.setStyleSheet(self.btn_style)
        self.nuke_project_layout.addWidget(self.nuke_dir_label)
        self.nuke_project_layout.addWidget(self.nuke_dir_edit)
        self.nuke_project_layout.addWidget(self.nuke_dir_btn)

        self.prefix_layout = QHBoxLayout()
        self.prefix_label = QLabel('Prefix Path:')
        self.prefix_edit = QLineEdit()
        self.prefix_edit.setText('//192.168.8.2/fx')
        self.replace_btn = QPushButton('Replace')
        self.replace_btn.clicked.connect(self._prefix_replace)
        self.replace_btn.setStyleSheet(self.btn_style)
        self.prefix_layout.addWidget(self.prefix_label)
        self.prefix_layout.addWidget(self.prefix_edit)
        self.prefix_layout.addWidget(self.replace_btn)

        self.nuke_root_tip = QLabel('')
        self._update_tip()

        self.project_btn_layout = QHBoxLayout()
        self.save_nk_btn = QPushButton('Save Nuke(Auto)')
        self.save_nk_btn.clicked.connect(self._save_nuke)
        self.save_nk_btn.setStyleSheet(self.btn_style)
        self.save_nk_btn.setFixedHeight(20)
        self.open_nkdir_btn = QPushButton('Show Nuke')
        self.open_nkdir_btn.clicked.connect(self._open_nuke_dir)
        self.open_nkdir_btn.setStyleSheet(self.btn_style)
        self.open_nkdir_btn.setFixedHeight(20)
        self.project_btn_layout.addWidget(self.save_nk_btn)
        self.project_btn_layout.addWidget(self.open_nkdir_btn)

        self.move_layout = QHBoxLayout()
        self.move_label = QLabel('Mov :')
        self.mov_list_comb = QComboBox()
        self.mov_list_comb.setMinimumWidth(330)
        self._init_mov_comb()
        self.update_mov_btn = QPushButton('⇵')
        self.update_mov_btn.clicked.connect(self._update_mov_items)
        self.update_mov_btn.setStyleSheet(self.btn_style)
        self.mov_dir_btn = QPushButton('Show Mov')
        self.mov_dir_btn.clicked.connect(self._open_mov_dir)
        self.mov_dir_btn.setStyleSheet(self.btn_style)
        self.move_layout.addWidget(self.move_label)
        self.move_layout.addWidget(self.mov_list_comb)
        self.move_layout.addWidget(self.update_mov_btn)
        self.move_layout.addWidget(self.mov_dir_btn)

        self.move_btn_layout = QHBoxLayout()
        self.save_move_btn = QPushButton('Save Mov')
        self.save_move_btn.clicked.connect(self._save_mov)
        self.save_move_btn.setStyleSheet(self.btn_style)
        self.save_move_btn.setFixedHeight(20)
        self.load_move_btn = QPushButton('Load Mov')
        self.load_move_btn.clicked.connect(self._load_mov)
        self.load_move_btn.setStyleSheet(self.btn_style)
        self.load_move_btn.setFixedHeight(20)
        self.to_deadline_btn = QPushButton('To Deadline')
        self.to_deadline_btn.clicked.connect(self._to_deadline)
        self.to_deadline_btn.setStyleSheet(self.btn_style)
        self.to_deadline_btn.setFixedHeight(20)
        self.move_btn_layout.addWidget(self.save_move_btn)
        self.move_btn_layout.addWidget(self.load_move_btn)
        self.move_btn_layout.addWidget(self.to_deadline_btn)

        self.submit_label = QLabel(u'提交')
        self.submit_label.setAlignment(Qt.AlignCenter)
        self.submit_label.setFont(self.mid_font)

        self.daily_layout = QHBoxLayout()
        self.daily_label = QLabel('DailyPath:')
        self.daily_label.setEnabled(False)
        self.daily_edit = QLineEdit()
        self.daily_edit.setEnabled(False)
        self.daily_edit.setText(self.daily_dir)
        self.daily_btn = QPushButton('...')
        self.daily_btn.setEnabled(False)
        self.daily_btn.setStyleSheet(self.btn_style)
        self.daily_btn.clicked.connect(self._get_daily_dir)
        self.daily_show_btn = QPushButton('show daily')
        self.daily_show_btn.clicked.connect(self._open_daily_dir)
        self.daily_show_btn.setEnabled(False)
        self.daily_show_btn.setStyleSheet(self.btn_style)
        self.daily_layout.addWidget(self.daily_label)
        self.daily_layout.addWidget(self.daily_edit)
        self.daily_layout.addWidget(self.daily_btn)
        self.daily_layout.addWidget(self.daily_show_btn)

        self.note_layout = QHBoxLayout()
        self.note_label = QLabel('task note:')
        self.note_text = QTextEdit()
        self.note_text.setMaximumHeight(50)

        # self.note_text.setEnabled(False)
        # self.note_btn=QPushButton('@提交note')
        # self.note_btn.clicked.connect(self._for_note)
        self.note_layout.addWidget(self.note_label)
        self.note_layout.addWidget(self.note_text)
        # self.note_layout.addWidget(self.note_btn)

        self.check_layout = QHBoxLayout()
        self.check_layout.setContentsMargins(0, 15, 0, 10)
        self.check_layout.setSpacing(25)
        self.check_layout.setAlignment(Qt.AlignCenter)
        self.check_daily = QCheckBox(u'提交到Dailies')
        self.check_daily.stateChanged.connect(self._daily_changed)
        # self.check_daily.setCheckState(Qt.Checked)
        self.check_mov = QCheckBox(u'提交mov到CGTW(触发note)')
        self.check_mov.setCheckState(Qt.Checked)
        self.check_cgtw = QCheckBox(u'打包到CGTW(不触发note)')
        self.check_cgtw.setCheckState(Qt.Checked)
        self.check_layout.addWidget(self.check_daily)
        self.check_layout.addWidget(self.check_mov)
        self.check_layout.addWidget(self.check_cgtw)



        self.btn_layout=QHBoxLayout()
        # self.load_btn=QPushButton(u'载入mov')
        # self.load_btn.setMinimumHeight(20)
        # self.load_btn.setStyleSheet(self.btn_style)
        # self.load_btn.clicked.connect(self._load_mov)
        # self.version_submit_btn=QPushButton(u'设置(自增版本)')
        # self.version_submit_btn.clicked.connect(self._save_update)
        # self.version_submit_btn.setMinimumHeight(20)
        # self.version_submit_btn.setStyleSheet(self.btn_style)
        # self.cover_submin_btn=QPushButton(u'设置(覆盖版本)')
        # self.cover_submin_btn.clicked.connect(self._save_cover)
        # self.cover_submin_btn.setMinimumHeight(20)
        # self.cover_submin_btn.setStyleSheet(self.btn_style)
        self.sumbit_btn=QPushButton(u'提交')
        self.sumbit_btn.setMinimumHeight(30)
        self.sumbit_btn.setEnabled(False)
        self.sumbit_btn.clicked.connect(self._sumbit)
        # self.sumbit_btn.setStyleSheet(self.btn_style)
        self.sumbit_btn.setStyleSheet(self.close_btn_style)
        # self.btn_layout.addWidget(self.load_btn)
        # self.btn_layout.addWidget(self.version_submit_btn)
        # self.btn_layout.addWidget(self.cover_submin_btn)
        self.btn_layout.addWidget(self.sumbit_btn)

        self.note_text.textChanged.connect(self._btn_limit)  # 控制按钮

        self.text_brower = QTextBrowser()
        self.main_layout.addWidget(self.project_setting_label)
        self.main_layout.addLayout(self.project_layout)
        self.main_layout.addLayout(self.eps_layout)
        self.main_layout.addLayout(self.artists_layout)
        self.main_layout.addLayout(self.pipeline_layout)
        self.main_layout.addLayout(self.shot_layout)

        self.main_layout.addLayout(self.task_name_layout)
        # self.main_layout.addLayout(self.mov_layout)
        # self.main_layout.addLayout(self.element_layout)
        self.main_layout.addLayout(self.artist_layout)
        self.main_layout.addLayout(self.fps_layout)
        self.main_layout.addLayout(self.frame_layout)
        self.main_layout.addLayout(self.show_info_layout)
        self.main_layout.addWidget(self.nuke_label)
        self.main_layout.addLayout(self.version_layout)
        self.main_layout.addLayout(self.nuke_project_layout)
        self.main_layout.addLayout(self.prefix_layout)
        self.main_layout.addWidget(self.nuke_root_tip)
        self.main_layout.addLayout(self.project_btn_layout)
        self.main_layout.addLayout(self.move_layout)
        self.main_layout.addLayout(self.move_btn_layout)
        self.main_layout.addWidget(self.submit_label)

        self.main_layout.addLayout(self.daily_layout)
        self.main_layout.addLayout(self.note_layout)
        self.main_layout.addLayout(self.check_layout)

        self.main_layout.addLayout(self.btn_layout)
        self.main_layout.addWidget(self.text_brower)

        self.setLayout(self.main_layout)

        self.timer = QBasicTimer()
        self.progress = MZProgresBar()
        self.progress.force_close_Signal.connect(self._force_close)
        self.thread_list =[]
        self.count = 0
        self.all_count = 0
        self.discopys = [] # 复制失败的帧
        self.all_path_list = []  # 所有文件对
        self.start_time = 0
        self.delta_time = 3
        self.file_cout = 0

        self.init_data()

    def event(self, event):
        # print('AAAA')
        if event.type()==QEvent.EnterWhatsThisMode:
            QWhatsThis.leaveWhatsThisMode()
            QMessageBox.about(self,u'操作说明',u'1.选择对应的项目Project,集数Eps,阶段Pipeline,镜头Shot,任务名称Task_name\n'
                                          u'2.如果cgtw上有已提交的mov会出现在mov列表里，可以对选择的mov进行载入mov导入nukemov����nuke\n'
                                          u'3.frame range为要输出的帧范围\n'
                                          u'4.DailyPath栏为默认的dailies路径，一般不需修改'
                                          u'5.选择提交到Dailies则会直接将Write输出到Dailies里，选择提交到CGTW，会将Write\n'
                                          u'输入到cgtw对应的目录下，同时触发cgtw提交。都选择则输出2次\n'
                                          u'6.载入mov: 导入选择的mov\n'
                                          u'7.设置(自增版本)与设置(覆盖版本)都是对选中的Write节点进行配置\n')
        return QDialog.event(self,event)

    def timerEvent(self, tevent):
        percent = self.count * 100 / (self.all_count + 0.00000001)
        print('percent:',percent)
        print('count:',self.count)
        print('all_count:',self.all_count)
        self.progress.set_percent(percent)


        # temp_list = []
        # err_list = []
        # for i in self.all_path_list:
        #     if os.path.exists(i[1]):
        #         temp_list.append(i[1])
        #     else:
        #         err_list.append(i[0])
        # self.discopys = err_list
        # print(u'discopys:',self.discopys)


        # if percent > 99.9 :
        #     if len(temp_list) == self.all_count:
        #         print(u'pack over')
        #         self.progress.close()
        #         self.timer.stop()
        #     else:
        #         print('file_cout:',self.file_cout)
        #         print('all_count:',self.all_count)

        if percent > 99.99:
            self.progress.close()
            self.timer.stop()
            print('stop do')
            for i in self.all_path_list:
                # print(i)
                if not os.path.exists(i[1]):
                    self.discopys.append(i[0])

            if self.discopys:
                QMessageBox.information(None,u'未提交文件','\n'.join(self.discopys))

    def _force_close(self,emit):
        print('_force_close:',emit)
        if emit:
            self.timer.stop()
        discopys = []
        for i in self.all_path_list:
            if not os.path.exists(i[1]):
                discopys.append(i[0])
        print('discopys:',discopys)
        if discopys:
            QMessageBox.information(None,u'未提交文件','\n'.join(self.discopys))


    def init_comb(self):
        """
        init drive letter
        :return:
        """
        drive_list=['ip...','A:\\','B:\\','C:\\','D:\\','E:\\','F:\\','G:\\','H:\\','I:\\','J:\\','K:\\','L:\\',
                    'M:\\','N:\\','O:\\','P:\\','Q:\\','R:\\','S:\\','T:\\',
                    'U:\\','V:\\','W:\\','X:\\','Y:\\','Z:\\']
        self.drive_comb.addItems(drive_list)
        self.drive_comb.setCurrentText('E:')

    def request_from_222(self,msg):
        """
        request data from 222
        :param msg: {'ask_type':xxx,''}
        :return:
        """
        # print(msg)
        data={}
        sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        sock.settimeout(0.35)
        try:
            sock.connect((self.HOST,self.PORT))
            sock.send(str(msg).encode())
            all_backs = b''
            while True:
                #time.sleep(0.1)
                print('接收中....')
                back = sock.recv(self.BUFFER)  # socket.MSG_WAITALL#,socket.MSG_WAITALL
                # # header_len=struct.unpack(back)
                # print('接受回来:', back)
                if not back:
                    break
                all_backs += back


        except Exception as request_from_222_ERR:
            print('request failed')
            print(str(request_from_222_ERR))
        finally:
            data = eval(all_backs.decode('utf8'))
            # print(data)
            sock.close()

        return data


    def create_shot(self,path,shot_info):
        """
        create project
        :param path: dir path
        :param shot_info: current shot infomation
        :return:
        """
        if not os.path.exists(path):
            os.makedirs(path)
        dir_list=['hip','geo','cam','abc','tex','fbx','img','nk','hda','DCC']
        for i in dir_list:
            dirs_path=os.path.join(path,i)
            if not os.path.exists(dirs_path):
                os.makedirs(dirs_path)


    def _open_project_window(self):
        """
        request 222 get project infomation
        :return:
        """
        self.project_list_window = ListModel()
        self.project_list_window.data_Signal.connect(self._get_project_info)
        msg = {'ask_type': 'project'}
        data = self.request_from_222(msg)
        self.project_list_window.set_data(data)
        self.project_list_window.show()

    def _get_project_info(self, data):
        self.current_project_data = data
        project_entity_name = data['entity_name']
        # print('_get_project_info 1:',data)
        msg = {'ask_type': 'config', 'entity_name': project_entity_name}
        try:
            self.current_project_config = self.request_from_222(msg)
            # print('_get_project_info 2:',self.current_project_config)
            self.current_project_config = self.current_project_config if self.current_project_config else {'fps': '',
                                                                                                           'color': '',
                                                                                                           'resolution': '',
                                                                                                           'path': '',
                                                                                                           'full_name': '',
                                                                                                           'entity_name': ''}
            # print('_get_project_info  self.current_project_data:',self.current_project_data)
            # print('_get_project_info  self.current_project_config:',self.current_project_config)
            self.choose_project_btn.setText(project_entity_name)
            self.fps_edit.setText(data['fps'])
            eps_list = data['eps_list'].split('|')
            # self.init_eps_comb(eps_list)
            self.eps_list = eps_list
        except Exception as _get_project_info_ERR:
            print(str(_get_project_info_ERR))


    def _open_eps_window(self):
        """
        打开集数窗口获取集数
        """
        if self.current_project_data:

            self.eps_win = EpsListWindow()
            self.eps_win.eps_Signal.connect(self._eps_changed)
            self.eps_win.set_list(self.eps_list)
            self.eps_win.show()

    def _eps_changed(self,current_eps):
        print('_eps_changed:',current_eps)
        self.task_name_comb.clear()
        # self.mov_list_comb.clear()
        self.eps_btn.setText(current_eps)
        self.shot_list_btn.setText('- -')
        if current_eps == 'Asset':
            self.artists_label.setVisible(True)
            self.artists_comb.setVisible(True)
            msg = {'ask_type':'account','cn_department':u'特效'} #这个仅给特效，写死
            artists_data = self.request_from_222(str(msg))
            # print('artists_data:',artists_data)
            self.current_artists = artists_data.get('artists',[])
            self.current_artists.insert(0,'')
            self.artists_comb.clear()
            self.artists_comb.addItems(self.current_artists)
        else:
            self.artists_label.setVisible(False)
            self.artists_comb.setVisible(False)

    def _artist_changed(self,artist):
        print('current artist:',artist)
        self.shot_list_btn.setText('- -')
        self.artist_show.setText(artist)
        msg = {'ask_type': 'artist_assets', 'database': self.current_project_data['database'],'artist':artist}
        asset_datas = self.request_from_222(str(msg))
        # print('asset_datas:',asset_datas)
        self.asset_data = asset_datas if asset_datas !=404 else {}

    def _pipeline_changed(self,pipeline):
        if pipeline=='Environment':
            self.daily_dir = r'\\192.168.1.248\3d\env\dailies'
            self.daily_edit.setText(self.daily_dir)
        self.task_name_comb.clear()

    def _task_name_changed(self,task_name):
        print('_task_name_changed:',task_name)
        # current_task_name = self.task_name_comb.currentText()
        if self.task_data:
            self.artist_show.setText(self.task_data[task_name]['artist'])

    def _patch_project_setting(self):
        # import nuke
        root = nuke.Root()
        start = root['first_frame'].value()
        end = root['last_frame'].value()
        self.start_edit.setText(str(int(start)))
        self.end_edit.setText(str(int(end)))





    def _init_version_comb(self):
        version_list = []
        for i in range(1,35):
            if i<10:
                verison = 'v00'+str(i)
            else:
                verison = 'v0'+str(i)
            version_list.append(verison)
        self.version_comb.addItems(version_list)


    def _update_current_version(self,signal=None):
        is_version = False
        version = 'v001'
        nk_path = None
        try:
            nk_path = nuke.root()['name'].value()
        except Exception as nuke_MISS:
            pass
        if nk_path:
            np = os.path.split(nk_path)[-1]
            name = os.path.splitext(np)[0]
            np_split = name.split('_')
            _version = np_split[-1]
            if version.startswith('v'):

                numb = version[1:]
                try:
                    inum = int(numb)
                    is_version = True
                    version = _version
                except Exception as num_ERR:
                    is_version = False

        self.current_version_label.setText(u'当前工程版本:{}'.format(version))
        current_version_comb = self.version_comb.currentText()
        if current_version_comb == version:
            self.current_version_label.setStyleSheet('QLabel{color : #77c40e}')
        else:
            self.current_version_label.setStyleSheet('QLabel{color : #ff8724}')


    def _init_nuke_dir(self):
        try:
            nuke_file = nuke.root()['name'].value()
            if nuke_file:
                self.nuke_dir_edit.setText(os.path.dirname(nuke_file))
        except Exception as nuke_ERR:
            pass

    def _init_mov_comb(self):
        nuke_dir = self.nuke_dir_edit.text()
        mov_dir = os.path.join(nuke_dir,'mov')
        if os.path.exists(mov_dir):
            mov_list = []
            for i in os.listdir(mov_dir):
                if i.endswith('mov'):
                    mov_list.append(i)
            self.mov_list_comb.clear()
            self.mov_list_comb.addItems(mov_list)
        else:
            os.makedirs(mov_dir)

    def _choose_nuke_dir(self):
        nuke_dir = QFileDialog.getExistingDirectory(self, u'选择目录')  # ,dir=hou.getenv('JOB')
        if nuke_dir:
            self.nuke_dir_edit.setText(nuke_dir)
            self._update_tip()
            self._update_mov_items()


    def _prefix_replace(self):
        """
        替换所有Read，Write前缀
         ['Camera2', 'ReadGeo2', 'Read','DeepRead'] : file
         Vectorfield : vfield_file
        """
        sn = nuke.allNodes()
        _prefix = self.prefix_edit.text()
        if _prefix.endswith('/'):
            _prefix = _prefix[:-1]

        for n in sn:
            c = n.Class()
            if c in ['Camera2', 'ReadGeo2', 'Read','DeepRead','Write']:
                file_path = n['file'].value()
                if ':' in file_path:
                    split_list = file_path.split(':')
                    split_list[0] = _prefix
                    new_path = ''.join(split_list)
                    n['file'].setValue(new_path)
            elif c == 'Vectorfield' :
                file_path = n['vfield_file'].value()
                if ':' in file_path:
                    split_list = file_path.split(':')
                    split_list[0] = _prefix
                    new_path = ''.join(split_list)
                    n['vfield_file'].setValue(new_path)

        QMessageBox.information(None, u'提示', u'路径替换完成')

    def _update_tip(self):
        try:
            not_in_root = u'Tip:当前nuke文件不在Nuke Direction下 !!! ,可Save Nuke(Auto)'
            in_root = u'Nuke文件位置正确'
            nuke_path = nuke.root()['name'].value()
            if not nuke_path:
                self.nuke_root_tip.setText(not_in_root)
                self.nuke_root_tip.setStyleSheet('QLabel{color : #ff8724}')
            else:
                nuke_dir_from_root = os.path.dirname(nuke_path)
                nuke_dir = self.nuke_dir_edit.text()
                if nuke_dir_from_root != nuke_dir:
                    self.nuke_root_tip.setText(not_in_root)
                    self.nuke_root_tip.setStyleSheet('QLabel{color : #ff8724}')
                else:
                    self.nuke_root_tip.setText(in_root)
                    self.nuke_root_tip.setStyleSheet('QLabel{color : #77c40e}')

        except Exception as nuke_Miss:
            pass

    def __saveNuke(self,nuke_dir):
        project = self.choose_project_btn.text()
        # eps = self.eps_comb.currentText()
        eps = self.eps_btn.text()
        pipeline_show = self.pipeline_comb.currentText()
        # pipeline = self.pipeline_map[pipeline_show]
        shot = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText() #if eps!='Asset' else ''
        version = self.version_comb.currentText()

        if project and eps and shot and task_name:

            nuke_file_name = '{}_{}_{}_{}_{}.nk'.format(project,eps,shot,task_name,version)
        # print('nuke_file_name:',nuke_file_name)
            nuke_file_path = os.path.join(nuke_dir,nuke_file_name)
            # nuke.scriptSave(nuke_file_path)
            nuke.scriptSaveAs(nuke_file_path)#,overwrite=1
            self._update_tip()
            self._update_current_version()
            QMessageBox.information(None, u'提示', u'当前nk已保存至\n{}'.format(nuke_file_path))
        else:
            QMessageBox.information(None,u'错误',u'当前项目路径不完整')


    def _save_nuke(self):
        nuke_dir = self.nuke_dir_edit.text()
        if nuke_dir:
            self.__saveNuke(nuke_dir)
            self._save_data()
        else:
            self._choose_nuke_dir()
            nuke_dir = self.nuke_dir_edit.text()
            if nuke_dir:
                self.__saveNuke(nuke_dir)
                self._save_data()

    def _save_data(self):
        """
        save nuke all choosed data
        """
        nuke_file_path = nuke.root()['name'].value()
        _dir, nuke_name = os.path.split(nuke_file_path)
        vname = os.path.splitext(nuke_name)[0]
        cfg_name = vname + '.cfg'
        cfg_path = os.path.join(_dir, cfg_name)
        data = {}
        # UI data
        data['current_project'] = self.choose_project_btn.text()
        data['eps'] = self.eps_btn.text()
        data['asset_artist'] = self.artists_comb.currentText()
        data['pipeline'] = self.pipeline_comb.currentText()
        data['shot'] = self.shot_list_btn.text()
        data['task_name'] = self.task_name_comb.currentText()
        data['artist_show'] = self.artist_show.text()
        data['fps'] = self.fps_edit.text()
        data['frame_start'] = self.start_edit.text()
        data['frame_end'] = self.end_edit.text()
        data['version'] = self.get_nk_version()
        data['nuke_direction'] = self.nuke_dir_edit.text()
        data['prefix_path'] = self.prefix_edit.text()

        # variable data
        data['current_artists'] = self.current_artists
        data['asset_data'] = self.asset_data
        data['current_asset'] = self.current_asset
        data['daily_path'] = self.daily_path
        data['cgtw_path'] = self.cgtw_path
        data['current_project_data'] = self.current_project_data
        data['current_project_config'] = self.current_project_config
        data['current_shot_info'] = self.current_shot_info
        data['task_data'] = self.task_data



        with open(cfg_path, 'w') as w:  # ,encoding='utf8'
            w.write(str(data))



    def get_nk_version(self):
        """
        get version by nk file name
        """
        nuke_file_path = nuke.root()['name'].value()
        nuke_name = os.path.split(nuke_file_path)[1]
        vname = os.path.splitext(nuke_name)[0]
        version = vname[-4:]
        if not version.startswith('v'):
            version = 'v001'
        return version

    def _open_nuke_dir(self):
        nuke_dir = self.nuke_dir_edit.text().replace('/','\\')
        os.startfile(nuke_dir)

    def _update_mov(self):
        self._update_mov_items()

    def _open_mov_dir(self):
        self._update_mov_items()
        nuke_dir = self.nuke_dir_edit.text()
        # current_mov = self.mov_list_comb.currentText()
        mov_dir = os.path.join(nuke_dir,'mov').replace('/','\\')#.replace('\\','/')
        if not os.path.exists(mov_dir):
            os.makedirs(mov_dir)
        os.startfile(mov_dir)

    def check_project(self):
        project = self.choose_project_btn.text()
        # eps = self.eps_comb.currentText()
        eps = self.eps_btn.text()
        # pipeline_show = self.pipeline_comb.currentText()
        # # pipeline = self.pipeline_map[pipeline_show]
        shot = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText()
        # version = self.version_comb.currentText()

        if project and eps and shot and task_name:
            return True
        else:
            return False


    def _save_mov(self):
        nuke_dir = self.nuke_dir_edit.text()
        if os.path.exists(nuke_dir):
            check = self.check_project()
            if check:
                current_write = self.get_current_write()
                if current_write not in [-1,0]:
                    print(u'当前Write:', current_write)
                    start = self.start_edit.text()
                    end = self.end_edit.text()
                    nuke.execute(current_write.name(),int(float(start)),int(float(end)),1)
                    mov_path = current_write['file'].value()
                    self._update_mov_items(os.path.split(mov_path)[-1])


                elif current_write == -1:
                    QMessageBox.information(None, u'错误', u'Write节点不存在')
            else:
                QMessageBox.information(None, u'错误', u'项目设置未完整')
        else:
            QMessageBox.information(None, u'错误', u'无效的Nuke Direction')


    def _load_mov(self):
        nuke_dir = self.nuke_dir_edit.text()
        current_mov = self.mov_list_comb.currentText()
        current_mov_path = os.path.join(nuke_dir,'mov',current_mov)
        if os.path.exists(current_mov_path):
            read = nuke.createNode('Read')
            read['file'].fromUserText(current_mov_path.replace('\\','/'))
            # read['file'].setValue()


    def _to_deadline(self):
        current_write = self.get_current_write()
        data = self._get_write_data(current_write)
        self.dealine_window = DeadlineWindow(data)
        self.dealine_window.show()

    def _update_mov_items(self,mov_name=None):
        self.mov_list_comb.clear()
        nuke_dir = self.nuke_dir_edit.text()
        mov_dir = os.path.join(nuke_dir,'mov')
        if not os.path.exists(mov_dir):
            os.makedirs(mov_dir)
        mov_list = []
        for i in os.listdir(mov_dir):
            if i.endswith('mov'):
                mov_list.append(i)
        mov_list = sorted(mov_list,reverse=True)
        self.mov_list_comb.addItems(mov_list)
        if mov_name:
            self.mov_list_comb.setCurrentText(mov_name)



    def _get_daily_dir(self):
        """
        get daily director path
        :return:
        """
        dir = QFileDialog.getExistingDirectory(self, u'选择目录')  # ,dir=hou.getenv('JOB')


    def _open_daily_dir(self):
        daily_dir = self.daily_edit.text().replace('/','\\')
        if not os.path.exists(daily_dir):
            os.makedirs(daily_dir)
        os.startfile(daily_dir)

    def _daily_changed(self,check):
        if check:
            self.daily_label.setEnabled(True)
            self.daily_edit.setEnabled(True)
            self.daily_btn.setEnabled(True)
            self.daily_show_btn.setEnabled(True)
        else:
            self.daily_label.setEnabled(False)
            self.daily_edit.setEnabled(False)
            self.daily_btn.setEnabled(False)
            self.daily_show_btn.setEnabled(False)


    def _btn_limit(self):
        current_note = self.note_text.toPlainText()
        if current_note:
            self.sumbit_btn.setEnabled(True)
            self.sumbit_btn.setStyleSheet(self.btn_style)
        else:
            self.sumbit_btn.setEnabled(False)
            self.sumbit_btn.setStyleSheet(self.close_btn_style)

    def _open_shot_window(self):
        """
        request 222, get shot info
        :return:
        """
        if self.current_project_data:
            database = self.current_project_data['database']
            # eps = self.eps_comb.currentText()
            eps = self.eps_btn.text()

            msg = {'ask_type': 'shot','database':database,'eps':eps}
            print(msg)
            data = {}
            if eps != 'Asset':
                data = self.request_from_222(msg)
            else: #资产只传基本名称进去，之后set_taskname时过滤读取
                # data = self.asset_data

                for v in self.asset_data.values():
                    entity_name = v['entity_name']
                    data[entity_name] = v

            self.shot_info_window = ShotListWindow()
            self.shot_info_window.shot_Signal.connect(self._get_shot_info)
            self.shot_info_window.set_data(data)
            self.shot_info_window.show()

    def set_task_name(self,data):
        """
        set the task_name_comb items
        :param data:
        :return:
        """
        self.task_name_comb.clear()
        if data:
            # print('set_task_name:',data)
            # print('set_task_name:',list(data.keys()))
            self.task_data=data
            task_name_list = list(data.keys())
            self.task_name_comb.addItems(task_name_list)
            current_task_name = self.task_name_comb.currentText()
            self.artist_show.setText(self.task_data[current_task_name]['artist'])
            self.current_asset = self.task_data[current_task_name]


    def _get_shot_info(self,data):
        """
        slot back shot data
        :param data:{'description': '���㣬�꣬���죬������ͷ���ˣ������������ˣ���', 'entity_name': 'FNDH100_0100',
        'img_path': '/upload/image/proj_fndh/min/591ec4e0a401d83bb1f1738c6846d35d.png', 'frame': '107'}
        :return:
        """
        # print('_get_shot_info data:',data)
        self.current_shot_info = data
        shot_name = data['entity_name']
        self.shot_list_btn.setText(shot_name)
        self.set_frame_range(data.get('frame', self.current_project_config['fps']))
        # eps = self.eps_comb.currentText()
        eps = self.eps_btn.text()
        pipeline_show = self.pipeline_comb.currentText()
        pipeline = self.pipeline_map[pipeline_show]
        cgtw_path = self.current_project_config['path']

        task_data = {}
        if eps != 'Asset':
            msg = {'ask_type': 'task', 'database': self.current_project_data['database'], 'eps': eps,'shot_name':shot_name,'pipeline':pipeline}
            # print('msg:',msg)
            task_data = self.request_from_222(msg)  #����þ�ͷ�����е�task_name��cgtw��task��id
            #print('task_data:',task_data)#{'efx': {'cg_id': 'proj_pltest,shot,B96FCF09-10BC-8127-6532-0AA84BFD26F3', 'artist': '杜江帆', 'task_name': 'efx'}}
        else: #当是资产时，传的data为：{entity_name:data,...}
            entity_name = data['entity_name']
            # task_name_list = []
            current_artist = self.artists_comb.currentText()  #资产的当前人员，已经确定
            for v in self.asset_data.values(): # self.asset_data为{cg_id:data,...}
                if v['entity_name'] == entity_name:
                    task_name = v['task_name']
                    v['artist'] = current_artist
                    # task_name_list.append(v['task_name'])
                    task_data[task_name] = v

        self.set_task_name(task_data)
        self._show_shot_info()

    def set_frame_range(self,frame):
        self.start_edit.setText('1')
        self.end_edit.setText(frame)
        try:
            root = nuke.Root()
            root['first_frame'].setValue(1)
            root['last_frame'].setValue(int(frame))
            root['fps'].setValue(int(self.fps_edit.text()))

        except Exception as set_frame_range_ERR:
            print('set_frame_range_ERR:',str(set_frame_range_ERR))

    def get_relative_data(self, cgtw_path, eps, shot_name, pipeline):
        data = {}
        if pipeline == 'mm':
            path = os.path.join(cgtw_path, 'Shot_work', 'Matchmove', eps)
            data = {}
            if os.path.exists(path):
                file_list = os.listdir(path)
                print('path:',path)
                for i in file_list:
                    name=i.split('_mm')[0]
                    if shot_name == name and i.endswith('.fbx') and not i.startswith('.'):
                        data[i] = os.path.join(path, i)
            # data[pipeline] = data
        if pipeline == 'ani':
            path = os.path.join(cgtw_path, 'Shot_work', 'Animation', eps,shot_name,'maya_file')
            data = {}
            if os.path.exists(path):
                file_list = os.listdir(path)
                for i in file_list:
                    name = i.split('_ani')[0]
                    if shot_name == name or i.endswith('.ma') or i.endswith('.abc') and not i.startswith('.'):
                        data[i] = os.path.join(path, i)
            # data[pipeline] = data
        if pipeline == 'env':
            path = os.path.join(cgtw_path, 'Shot_work', 'Environment', eps,'Render')
            data = {}
            if os.path.exists(path):
                file_list = os.listdir(path)
                for i in file_list:
                    name = i.split('_env')[0]
                    if shot_name == name and not i.startswith('.'):
                        data[i] = os.path.join(path, i)
            # data[pipeline] = data
        return data

    def get_mov_list(self,cgtw_path, eps, shot_name, pipeline):
        path = os.path.join(cgtw_path, 'Shot_work', pipeline, eps)
        print('get_mov_list: path:',path)
        print('get_mov_list: pipeline:', pipeline)
        # data = {}
        mov_list = []
        if os.path.exists(path):
            file_list = os.listdir(path)
            for i in file_list:
                name = i.split('_efx')[0] if pipeline == 'FX' else i.split('_env')[0]
                if shot_name == name and not i.startswith('.'):
                    # data[i] = os.path.join(path, i)
                    # mov_list.append(os.path.join(path, i))
                    mov_list.append(i)
        return mov_list


    def init_config(self, config_path):
        config_data = {}
        if os.path.exists(config_path):
            with open(config_path, 'r') as r:  # ,encoding='utf8'
                config_data = eval(r.read())
        # print('config_data:', config_data)
        return config_data

    def init_data(self):
        try:
            nuke_file_path = nuke.root()['name'].value()
            _dir,nuke_name = os.path.split(nuke_file_path)
            vname = os.path.splitext(nuke_name)[0]
            cfg_name = vname+'.cfg'
            cfg_path = os.path.join(_dir,cfg_name)
            data = {}
            if os.path.exists(cfg_path):
                with open(cfg_path, 'r') as r:  # ,encoding='utf8'
                    data = eval(r.read())
            # print('data:', data)
            self.__init_data(data)
        except Exception as init_data_ERR:
            print(init_data_ERR)


    def __init_data(self,data):
        """
        init ui and variables
        """
        if data:
            # init variable
            # self.current_project = data['current_project']
            # self.current_eps = data['current_eps']
            self.current_artists = data['current_artists']
            self.asset_data = data['asset_data']
            self.current_asset = data['current_asset']
            # self.current_shot = data['current_shot']
            self.daily_path = data['daily_path']
            self.cgtw_path = data['cgtw_path']
            self.current_project_data = data['current_project_data']
            self.current_project_config = data['current_project_config']
            self.current_shot_info = data['current_shot_info']
            self.task_data = data['task_data']
            # init UI
            self.choose_project_btn.setText(data['current_project'])
            self.eps_btn.setText(data['eps'])
            self.artists_comb.addItems(data['current_artists'])
            self.artists_comb.setCurrentText(data['asset_artist'])
            self.pipeline_comb.setCurrentText(data['pipeline'])
            self.shot_list_btn.setText(data['shot'])
            self.task_name_comb.addItem(data['task_name'])
            self.artist_show.setText(data['artist_show'])
            self.fps_edit.setText(data['fps'])
            self.start_edit.setText(data['frame_start'])
            self.end_edit.setText(data['frame_end'])
            self.version_comb.setCurrentText(data['version'])
            self.nuke_dir_edit.setText(data['nuke_direction'])
            self.prefix_edit.setText(data['prefix_path'])


    def init_project_comb(self, data):
        """
        init project_comb items
        :param data:
        :return:
        """
        if data:
            self.project_comb.clear()
            self.project_comb.addItems(sorted(list(data.keys())))

    # def init_eps_comb(self,eps_list):
    #     """
    #     init eps items
    #     :return:
    #     """
    #     self.eps_comb.clear()
    #     s_list = sorted(eps_list)
    #     s_list.insert(0, 'Asset')
    #     s_list.insert(0, '')
    #     self.eps_comb.addItems(s_list)
    #     self.current_eps = self.eps_comb.currentText()


    # def init_shot_comb(self):
    #     """
    #     init shot comb items
    #     :return:
    #     """
    #     current_project = self.project_comb.currentText()
    #     current_eps = self.eps_comb.currentText()
    #     if current_project and current_eps:
    #         shot_dir = os.path.join(self.project_root_path, current_project, current_eps)
    #         if os.path.exists(shot_dir):
    #             shot_list = os.listdir(shot_dir)
    #             self.shot_comb.clear()
    #             self.shot_comb.addItems(sorted(shot_list))

    def init_pipeline_comb(self):
        pipeline_list = ['FX','CFX','FX_Cloth','FX_Crowd','FX_Previs','FX_Hair','Environment','Env_Postviz','Rig']
        self.pipeline_comb.addItems(pipeline_list)



    def _show_shot_info(self):#, shot_info
        """
        pipeline changed  update the shot info
        :return:
        """
        # show_text = ''
        if self.current_shot_info:
            # print(shot_info)
            show_text ='项目: {}'.format(self.current_project_data['full_name'])+'\n'+'FPS: {}'.format(self.current_project_data['fps'])+'\n' \
                        +'分辨率: {}'.format(self.current_project_config.get('resolution','')+'\n'+'项目路径: {}'.format(self.current_project_config.get('path','')))+'\n'\
                       +'帧数: {}'.format(self.current_shot_info.get('frame','')  +'\n' + '制作内容: {}'.format(self.current_shot_info.get('description','')))
            self.text_brower.setText(show_text)


    def _get_cgtw_render_dir(self):

        cgtw_dir_path = ''
        pipeline = self.pipeline_comb.currentText()
        shot_name = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText()
        # eps = self.eps_comb.currentText()
        eps = self.eps_btn.text()
        cgtw_path = self.current_project_config.get('path','')
        project = self.choose_project_btn.text()

        if project and eps and shot_name and task_name:
            if cgtw_path and shot_name and eps:
                if eps != 'Asset':
                    cgtw_dir_path = os.path.join(cgtw_path, 'Shot_work', pipeline, eps, 'Render')
                else:
                    cgtw_dir_path = os.path.join(cgtw_path, 'Asset_work', pipeline, shot_name, 'Render')
        return cgtw_dir_path


    def _open_cgtw_render_dir(self):
        """
        打开提交到cgtw的路径
        """
        cgtw_submitFile_path = self._get_cgtw_submitFile_path().replace('/','\\')
        if os.path.exists(cgtw_submitFile_path):
            os.startfile(cgtw_submitFile_path)
        else:
            render_dir = os.path.dirname(cgtw_submitFile_path)
            if os.path.exists(render_dir):
                os.startfile(render_dir)
            else:
                QMessageBox.information(None,'错误','信息不正确')


    # def save_new_file(self, new_name):
    #     """
    #     slot from name window ,save new file
    #     :param new_name:
    #     :return:
    #     """
    #     drive = self.drive_btn.text()
    #     project = self.choose_project_btn.text()
    #     # eps = self.eps_comb.currentText()
    #     eps = self.eps_btn.text()
    #     shot = self.shot_list_btn.text()
    #     pipeline = self.pipeline_comb.currentText()
    #     if project != '- -' and shot != '- -' and eps:
    #         dir_path = os.path.join(drive, project, eps, shot, pipeline)
    #         hip_name = shot + '_' + pipeline + '_' + new_name + '_v001.hip'  # project+'_'+eps+'_'+
    #         hip_path = os.path.join(dir_path, 'hip', hip_name)
    #         print(dir_path)
    #         print(hip_path)
    #         self.create_shot(dir_path, self.current_shot_info)


    # def _save_file(self):
    #     """
    #     save current hip to the path as its shot name
    #     :return:
    #     """
    #     new_file = ''
    #     # current_shot_name=self.current_shot.currentText()
    #     self.name_window = Name()
    #     self.name_window.name_Signal.connect(self.save_new_file)
    #     self.name_window.show()


    def int2str(self,number):
        if number < 10:
            return 'v00' + str(number)
        elif number < 100:
            return 'v0' + str(number)
        else:
            return 'v' + str(number)

    def update_version(self,ori_version):
        new_file_name = ''
        file_name, ex_name = os.path.splitext(ori_version) #a_b_v001.mov
        slite_files = file_name.split('_')#[a,b,v001]
        vers = slite_files[-1]
        slite_files.remove(vers)
        if vers.startswith('v'):
            num = vers[1:]
            new_ver = int(num) + 1
            version = self.int2str(new_ver)
            slite_files.append(version)
            new_file_name = '_'.join(slite_files) + ex_name
        else:
            new_file_name = file_name + '_v001' + ex_name
        return new_file_name

    # def _save_update(self):
    #     """
    #     autosave file update version
    #     """
    #     pipeline = self.pipeline_comb.currentText()
    #     pipeline_name = self.pipeline_map[pipeline]  # self.pipeline_nas_map[pipeline]
    #     # eps = self.eps_comb.currentText()
    #     eps = self.eps_btn.currentText()
    #     element = self.element_edit.text()
    #     cgtw_path = self.current_project_config['path']
    #     pre_daily_dir_path = self.daily_edit.text()
    #     current_mov = self.mov_list_comb.currentText()
    #     new_file = ''
    #     if current_mov:
    #         new_file = self.update_version(current_mov)
    #         print('new_mov_name:', new_file)
    #     else:
    #         shot_name = self.shot_list_btn.text()
    #         new_file = shot_name + '_' + pipeline_name + '_{}_v001.mov'.format(element)
    #         if pipeline_name == 'env':
    #             new_file = shot_name + '_' + pipeline_name + '_v001.mov'
    #
    #         print('No:', new_file)
    #     cgtw_mov_path = os.path.join(cgtw_path, 'Shot_work', pipeline, eps, new_file)
    #     self.cgtw_path = cgtw_mov_path
    #     print('cgtw_mov_path:', cgtw_mov_path)
    #
    #     #get daily path
    #     daily_dir_path = self.get_daily_dir_path()
    #
    #     check_status = self.check_path_status()
    #     if check_status == 1:  # ���ύdaily
    #         self.daily_path = os.path.join(daily_dir_path, new_file)
    #         print('daily_path:', self.daily_path)
    #         self.write_daily(self.daily_path)
    #     if check_status == 2:  # ���ύ��
    #         self.write_daily(self.cgtw_path)
    #     if check_status == 3:  # ���ύcgtw
    #         self.write_daily(self.cgtw_path)

    def _get_cgtw_mov_path(self):
        """
        获取cgtw上mov提交绝对路径
        """
        cgtw_mov_path = ''
        pipeline = self.pipeline_comb.currentText()
        pipeline_name =self.pipeline_map[pipeline] #self.pipeline_nas_map[pipeline]
        shot_name = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText()
        # eps = self.eps_comb.currentText()
        eps = self.eps_btn.text()
        cgtw_path = self.current_project_config.get('path','')
        mov = self.mov_list_comb.currentText()

        project = self.choose_project_btn.text()
        version = self.version_comb.currentText()
        # print("_get_cgtw_mov_path:",project, eps , shot_name , task_name,cgtw_path)
        if project and eps and shot_name and task_name:
            cgtw_mov_pre = '{}_{}_{}.mov'.format(shot_name,task_name,version)

            if mov == cgtw_mov_pre:  #同镜头任务，可提交
                if cgtw_path and shot_name and eps and mov:
                    if eps!='Asset':
                        cgtw_mov_path = os.path.join(cgtw_path, 'Shot_work', pipeline, eps, mov)
                    else:
                        cgtw_mov_path = os.path.join(cgtw_path, 'Asset_work', pipeline,shot_name,mov)
            else:
                QMessageBox.information(None,u"错误",'提交mov名称或版本不匹配')

        return cgtw_mov_path

    def _get_project_dir(self):
        project_dir = ''
        # pipeline = self.pipeline_comb.currentText()
        # pipeline_name =self.pipeline_map[pipeline] #self.pipeline_nas_map[pipeline]
        shot_name = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText()
        # eps = self.eps_comb.currentText()
        eps = self.eps_btn.text()

        project = self.choose_project_btn.text()
        version = self.version_comb.currentText()

        if project and eps and shot_name and task_name:
            project_dir = '{}_{}_{}'.format(shot_name,task_name,version)
        # else:
        #     QMessageBox.information(None, u"错误", '提交mov与所选镜头不匹配')

        return project_dir

    def _get_cgtw_submitFile_path(self):
        """
        获取cgtw上提交的渲染文件目录绝对路径
        """
        # cgtw_mov_path = self._get_cgtw_mov_path()
        project_dir = self._get_project_dir()
        # cgtw_dir_path = os.path.dirname(cgtw_mov_path)
        # cgtw_render_dir = os.path.join(cgtw_dir_path,'Render')
        cgtw_render_dir = self._get_cgtw_render_dir()
        cgtw_submit_file_path = os.path.join(cgtw_render_dir,project_dir)

        return cgtw_submit_file_path



    def get_daily_dir_path(self):
        """
        ��ȡdaily mov�����Ŀ¼�����������Լ����������
        :return:
        """
        daily_dir_path = ''
        pre_daily_dir_path = self.daily_edit.text()
        # current_mov = self.mov_list_comb.currentText()
        _pipeline = self.pipeline_comb.currentText()
        pipeline = self.pipeline_map[_pipeline]
        date,apm = self.get_date(pipeline)
        if apm:
            daily_dir_path=os.path.join(pre_daily_dir_path,date,apm)
        else:
            daily_dir_path=os.path.join(pre_daily_dir_path,date)
        return daily_dir_path






    # def get_daily_mov_path(self):
    #     """
    #     submit to the daily path
    #     :return:
    #     """
    #     daily_mov_path = ''
    #     if self.current_write:
    #         file_path = self.current_write['file'].value()
    #         mov = os.path.split(file_path)[1]
    #         daily_dir_path = self.get_daily_dir_path()
    #         daily_mov_path = os.path.join(daily_dir_path, mov)
    #     return daily_mov_path,daily_dir_path

    # def _save_cover(self):
    #     pipeline = self.pipeline_comb.currentText()
    #     pipeline_name =self.pipeline_map[pipeline] #self.pipeline_nas_map[pipeline]
    #     task_name = self.task_name_comb.currentText()
    #     eps = self.eps_comb.currentText()
    #     cgtw_path = self.current_project_config['path']
    #     pre_daily_dir_path = self.daily_edit.text()
    #     # current_mov = self.mov_list_comb.currentText()
    #
    #     shot_name=self.shot_list_btn.text()
    #     element = self.element_edit.text()
    #     # new_file = shot_name + '_' + pipeline_name + '_{}_v001.mov'.format(element)
    #     # new_file = shot_name + '_' + task_name + '_{}_v001.mov'.format(element)
    #     new_file = shot_name + '_efx_{}_v001.mov'.format(element)  # eg:HYX-05-03-efx_element_v001.mov
    #     if pipeline_name=='env':
    #         # new_file = shot_name + '_' + pipeline_name + '_v001.mov'
    #         new_file = shot_name + '_' + task_name + '_v001.mov'
    #     # if self.mov_list_comb.findText(new_file) < 0:
    #     #     self.mov_list_comb.addItems([new_file])
    #     # self.mov_list_comb.setCurrentText(new_file)
    #     # print('No:', new_file)
    #     if eps!='Asset':
    #         cgtw_mov_path = os.path.join(cgtw_path, 'Shot_work', pipeline, eps, new_file)
    #     else:
    #         cgtw_mov_path = os.path.join(cgtw_path, 'Asset_work', pipeline,shot_name,new_file)
    #     self.cgtw_path = cgtw_mov_path
    #     print('cgtw_mov_path:', cgtw_mov_path)
    #
    #     daily_dir_path = ''
    #     date, apm = self.get_date(pipeline)
    #     if apm:
    #         daily_dir_path = os.path.join(pre_daily_dir_path, date, apm)
    #     else:
    #         daily_dir_path = os.path.join(pre_daily_dir_path, date)
    #
    #     if self.check_daily.isChecked():
    #         if not self.check_cgtw.isChecked():  # ���ύ��daily
    #             self.daily_path = os.path.join(daily_dir_path, new_file)
    #             print('daily_path:', self.daily_path)
    #             self.write_daily(self.daily_path)
    #
    #         else:  # cgtwҲ��ѡ���ˣ���ôwrite��Ӧ����cgtw��·��
    #             self.write_daily(self.cgtw_path)
    #     else:
    #         if self.check_cgtw.isChecked():
    #             self.write_daily(self.cgtw_path)

    def check_path_status_ori(self):
        status=0  #û��ѡ
        if self.check_daily.isChecked():
            if not self.check_cgtw.isChecked():
                status=1  #���ύdaily
            else:
                status=2  #���ύ
        else:
            if self.check_cgtw.isChecked():
                status=3  #��cgtw�ύ

        return status

    def check_path_status(self):
        status=0  #
        if self.check_daily.isChecked():
            if not self.check_cgtw.isChecked():
                status=1  #���ύdaily
            else:
                status=2  #���ύ
        else:
            if self.check_cgtw.isChecked():
                status=3  #��cgtw�ύ

        return status



    def cmd_cgtw_submit(self,database,module,task_id,mov,note):# 6.1
        """
        �ύ��cgtw
        :param database:
        :param module:
        :param task_id:
        :param mov: mov名称
        :param note:
        :return:
        """
        cmd = '''"{}" "{}" "{}" "{}" "{}" "{}" "{}"'''.format(self.cgtwpy_path,self.scripy_path,database,module,task_id,mov,note)#,movpath
        print('cmd:',cmd)
        import subprocess
        subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        print('submit over')


    def cmd_cgtw_note(self,database,module,task_id,note):#,movpath
        """
        �ύ��cgtw
        :param database:
        :param module:
        :param shot:
        :param task_id:
        :param movpath:
        :return:
        """

        print('ori_note',note)
        print('note:',note.replace('\\','\\\\'))
        # cmd = u'''"{}" "{}" {} "{}" "{}"'''.format(self.cgtwpy_path,self.note_path,database,task_id,note)#,movpath
        cmd = [self.cgtwpy_path,self.note_path,database,module,task_id,json.dumps(note)]

        print('cmd_note:',cmd)
        import subprocess
        subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
        print('note over')

    # def read_info_ori(self,dir_path,nuke_name):
    #     """
    #     ��ȡȫ�ִ����Ϣ
    #     :param dir_path: nuke������ļ�Ŀ¼ \\...shot_name_v00x
    #     :param nuke_name: test.nk ���ļ�����β׺
    #     :return: #{'Read1':['Read',path],'Read2:'['Read',path],'Camera1':['Camera2',path]}
    #      {'Read1':}
    #     """
    #     # import nuke
    #     nkname=os.path.splitext(nuke_name)[0]
    #     save_path = os.path.join(dir_path, nuke_name)  # E:/AA/test/test.nk
    #     self.save_path=save_path
    #     if not os.path.exists(dir_path):
    #         os.makedirs(dir_path)
    #     data = {}
    #     sn = nuke.allNodes()
    #     for n in sn:
    #         # n.Class()
    #         name = n.name()
    #         if n.Class() in ['Camera2', 'ReadGeo2', 'Read','DeepRead']:  #, 'Write'  ['Camera2', 'ReadGeo2', 'Read','DeepRead'] Vectorfield/vfield_file
    #             file = n['file'].value()
    #             file_name = os.path.split(file)[1]
    #             data[name] = [n.Class(), file]
    #             new_path = os.path.join('footage', n.Class(), name, file_name)  # footage/Read/read1/aa.text
    #             n['file'].setValue(new_path.replace('\\', '/'))
    #         elif n.Class() == 'Vectorfield':
    #             file = n['vfield_file'].value()
    #             file_name = os.path.split(file)[1]
    #             data[name] = [n.Class(), file]
    #             new_path = os.path.join('footage', n.Class(), name, file_name)
    #             n['vfield_file'].setValue(new_path.replace('\\', '/'))
    #     rt = nuke.Root()
    #     rt['project_directory'].setValue(dir_path.replace('\\', '/'))
    #     # nuke.scriptSave(save_path)
    #     project_data = {'project': nkname, 'data': data}
    #     self.nk_data=project_data
    #     # print('data:', project_data)
    #     return project_data

    def read_info(self,cgtw_render_dir,project_dir):#,nuke_name
        """
        获取所有工程与节点路径信息
        :param cgtw_render_dir: cgtw上的文件提交路径
        :param project_dir: 项目文件夹名称
        :return:
         {'read1':{'scr_path':xxx,'cgtw_file_dir_path':xxx},'read2':{'scr_path':xxx,'cgtw_file_dir_path':xxx},...}
        """
        # import nuke
        # root = nuke.Root()
        # nuke_name = root['name'].value()
        # nkname = os.path.splitext(nuke_name)[0]  # xxxx_v001 不带.nk
        # save_path = os.path.join(cgtw_dir_path, nuke_name)  # E:/AA/test/test.nk
        # self.save_path = save_path

        cgtw_submit_dir = os.path.join(cgtw_render_dir,project_dir)
        if not os.path.exists(cgtw_submit_dir):
            os.makedirs(cgtw_submit_dir)

        data = {}
        ct = str(time.time())
        sn = nuke.allNodes()
        for n in sn:
            # n.Class()
            name = n.name()
            uname = name+'_'+ct

            if n.Class() in ['Camera2', 'ReadGeo2', 'Read','DeepRead'] :  #, 'Write'
                outputs = n.dependent(nuke.INPUTS)
                disable = n['disable'].value()
                if outputs and not disable:
                    n['label'].setValue(uname)
                    file_path = n['file'].value()
                    dir_path, hold_file = os.path.split(file_path)
                    file_pre_name = hold_file.split('.')[0].replace('#', '').replace('_%04d', '').replace('%04d', '').replace('%4d','').replace('%d','')
                    cgtw_file_dir_path = os.path.join(cgtw_submit_dir,'footage', name+'_'+file_pre_name).replace('\\', '/')  # footage/read1_xxx_xxx_v001/xxx_xxx_v001
                    data[uname] = {'scr_path':file_path,'cgtw_file_dir_path':cgtw_file_dir_path}

            elif n.Class() == 'Vectorfield':
                outputs = n.dependent(nuke.INPUTS)
                disable = n['disable'].value()
                if outputs and not disable:
                    n['label'].setValue(uname)
                    file_path = n['vfield_file'].value()
                    # file_name = os.path.split(file_path)[1]
                    dir_path, hold_file = os.path.split(file_path)
                    file_pre_name = hold_file.split('.')[0].replace('#', '').replace('_%04d', '').replace('%04d', '').replace('%4d','').replace('%d','')
                    cgtw_file_dir_path = os.path.join(cgtw_submit_dir,'footage',name+'_'+file_pre_name).replace('\\', '/')
                    data[uname] = {'scr_path': file_path, 'cgtw_file_dir_path': cgtw_file_dir_path}

        project_data = {'cgtw_submit_dir': cgtw_submit_dir, 'data': data}
        # self.nk_data = project_data
        # print('data:', project_data)
        return project_data


    def show_sequence(self,dir_path, base_name):
        """
        获取dir_path下带base_name的文件
        :param dir_path:
        :param base_name: �ļ�ͨ������
        :return:
        """
        sequence = []
        file_names = []
        file_list = os.listdir(dir_path)
        # print('file_list:',file_list)
        for i in file_list:
            abs_path = os.path.join(dir_path, i)
            if os.path.isfile(abs_path):
                file_names.append(i)
                if base_name in i:
                    sequence.append(abs_path)
        return sequence, file_names

    def check_file(self,path):
        u"""
        传入一个nuke中的file路径(带%04或####)，返回该路径下对应的所有文件路径列表file_path_list,以及文件名称列表name_list
        :param path:
        :return:
        """
        file_path_list = []
        name_list = []

        dir_path, file_name = os.path.split(path)
        if file_name.count('%04d') > 0:
            print(u'是序列')
            base_name = file_name.split('%04d')[0]
            file_path_list, name_list = self.show_sequence(dir_path, base_name)
        elif file_name.count('%d') > 0:
            print(u'是序列')
            base_name = file_name.split('%d')[0]
            file_path_list, name_list = self.show_sequence(dir_path, base_name)
        else:
            if os.path.isfile(path):
                file_path_list = [path]
                name_list = [os.path.split(path)[1]]
                print(u'不是序列')
                print('file_path_list:',file_path_list)
                print('name_list:',name_list)

        return file_path_list, name_list



    def get_copy_paths(self,origin_paths, name_list, dir_path):
        """
        获取复制到cgtw上的文件路径
        """
        copy_paths = []
        if not os.path.exists(dir_path) and name_list:  # 仅当存在文件名称时才创建远程路径
            os.makedirs(dir_path)
        for i in origin_paths:
            des = os.path.join(dir_path, name_list[origin_paths.index(i)])
            copy_paths.append((i,des))
        return copy_paths

    def clip_list(self,a, c):  #
        clip_back = []
        if len(a) > c:
            for i in range(int(len(a) / c)):
                # print(i)
                clip_a = a[c * i:c * (i + 1)]
                clip_back.append(clip_a)


            last = a[int(len(a) / c) * c:]
            if last:
                clip_back.append(last)
        else:
            clip_back = [a]

        return clip_back


    def setLabel(self):
        """
        给每个read节点添加label
        """
        nodes = nuke.allNodes()
        for n in nodes:
            if n.Class() == 'Read':
                n['label'].setValue(n.name() + '_' + str(time.time()))



    def pack(self):
        """
        # ,cgtw_dir_path,nkfile
        :param cgtw_dir_path: �����Ŀ¼  \\\\192.168.1.239\\cgteamwork4\\PLTEST\\Shot_work\\FX\\eps01\\Render\\tam05_01_003_efx_element_v001
        :param nkfile:  test.nk ���ļ�β׺������
        :return:
        """
        print('pack start')
        cgtw_mov_path = self._get_cgtw_mov_path()
        if cgtw_mov_path:
            project_dir = self._get_project_dir()
            cgtw_dir_path = os.path.dirname(cgtw_mov_path)
            cgtw_render_dir = os.path.join(cgtw_dir_path,'Render')

            self.count = 0
            self.file_cout = 0
            self.all_count = 0
            self.discopys = []
            self.all_path_list = []
            if self.thread_list:
                for t in self.thread_list:
                    t.quit()
                    t.wait()
            print('pack 001')
            info_data = self.read_info(cgtw_render_dir,project_dir)
            # print('info_data:',info_data)

            cgtw_submit_dir = info_data['cgtw_submit_dir'] #//.../Shot_work/FX/eps/Render/xxx_v001
            # save nuke file
            nuke_file_path = nuke.root()['name'].value()
            nuke_name = os.path.split(nuke_file_path)[1]
            cgtw_nuke_path = os.path.join(cgtw_submit_dir,nuke_name)
            nuke.scriptSave(cgtw_nuke_path)

            # save config
            config_path = os.path.join(cgtw_submit_dir,'config.json')
            with open(config_path,'w') as w:
                w.write(json.dumps(info_data))
            print('config completed!')
            # return
            # copy file
            data = info_data['data']
            all_path_list = []
            for k, v in data.items():
                scr_path = v['scr_path']
                cgtw_file_dir_path = v['cgtw_file_dir_path']
                file_paths, name_list = self.check_file(scr_path)
                # self.all_count += len(file_paths)

                copy_paths = self.get_copy_paths(file_paths, name_list, cgtw_file_dir_path)
                # print('copy_paths:',copy_paths)
                all_path_list.extend(copy_paths)

            self.all_count = len(all_path_list)
            print('all_count:', self.all_count)
            # print('all_path_list:')
            # for f in all_path_list:
            #     print(f)
            self.all_path_list = all_path_list
            print('check point')
            cliped_list = self.clip_list(all_path_list, 10)
            # print('cliped_list:',cliped_list)
            self.progress.show()
            #print('progress show')
            # c = int(len(all_path_list)/1000)
            # it = c*800 if c > 1 else 1000
            # self.timer.start(it, self)
            self.timer.start(800, self)
            # self.start_time = time.time()
            thread_list = []
            for i in cliped_list:
                th = CopyThread(i, self)
                thread_list.append(th)
                th.start()
            self.thread_list = thread_list



    #
    # def _copy_save(self):
    #     """
    #
    #     :return:
    #     """
    #     # import nuke
    #     # nuke.scriptSave("")
    #     # shutil.copyfile(self.current_nuke_path,self.save_path)
    #     os.system('copy "%s" "%s"' % (self.current_nuke_path, self.save_path))
    #     # win32file.CopyFile(self.current_nuke_path,self.save_path,1)
    #     # self.reset_paths()
    #     # nuke.scriptSave('')

    # def reset_paths(self):
    #     """
    #
    #     :return:
    #     """
    #     # import nuke
    #     #self.nk_data ={'project':'FNDH','data':{'Read1':['Read','E:/AA.exr'],'vlt':['vfield_file','E:/vv/la.lvt']}}
    #     if self.nk_data:
    #         data=self.nk_data['data']
    #         for k,v in data.items():
    #             node=nuke.toNode(k)
    #             nodetype=v[0]
    #             filepath=v[1]
    #             file_path_name='file' if nodetype!='Vectorfield' else 'vfield_file'
    #             node[file_path_name].setValue(filepath)
    #         root=nuke.Root()
    #         root['project_directory'].setValue('')
    #     print('reset_paths done')



    def _submit_daily(self):
        """
        copy current mov to the daily path
        """
        result = u'失败'
        nuke_dir = self.nuke_dir_edit.text()
        mov = self.mov_list_comb.currentText()
        current_mov_path = os.path.join(nuke_dir,'mov',mov)
        if os.path.exists(current_mov_path):
            daily_dir_path = self.get_daily_dir_path()
            if not os.path.exists(daily_dir_path):
                os.makedirs(daily_dir_path)
            daily_mov_path = os.path.join(daily_dir_path, mov)
            # shutil.copy(current_mov_path,daily_mov_path)
            os.system('copy "%s" "%s"' % (current_mov_path, daily_mov_path))
            result = u'成功'

        return result

    def _submit_mov(self):
        result = u'失败'
        # get shot info
        cgtw_mov_path = self._get_cgtw_mov_path()
        print('_submit_mov cgtw_mov_path:', cgtw_mov_path)
        if cgtw_mov_path:
            nuke_dir = self.nuke_dir_edit.text()
            mov = self.mov_list_comb.currentText()
            current_mov_path = os.path.join(nuke_dir,'mov',mov)
            if current_mov_path:
                # shutil.copy(current_mov_path,cgtw_mov_path)
                cgtw_mov_dir = os.path.dirname(cgtw_mov_path)
                if not os.path.exists(cgtw_mov_dir):
                    os.makedirs(cgtw_mov_dir)
                os.system('copy "%s" "%s"' % (current_mov_path, cgtw_mov_path))

                database = self.current_project_data['database']
                # eps = self.eps_comb.currentText()
                eps = self.eps_btn.text()
                shot = self.shot_list_btn.text()
                if sys.version<'3':
                    task_name = self.task_name_comb.currentText().encode('utf-8') if eps != 'Asset' else ''
                else:
                    task_name = self.task_name_comb.currentText()
                cg_id = self.task_data[task_name]['cg_id'] if eps != 'Asset' else self.current_asset['cg_id']
                task_id = cg_id.split(',')[2] #if eps != 'Asset' else ''
                # if eps != 'Asset':
                module = 'shot' if eps != 'Asset' else 'asset'
                # self.cmd_cgtw_submit(database, module,shot, task_id)  # 5.3

                note = self.note_text.toPlainText().replace(' ', '_').replace(',', '_')
                if note:
                    self.cmd_cgtw_note(database, module, task_id, note)
                self.cmd_cgtw_submit(database, module, task_id,mov,note)
                # self.cmd_cgtw_submit(database, module, task_id,cgtw_mov_path,note)
                result = u'成功'

        return result


    # def submit_note(self):
    #     """
    #     提交note
    #     """
    #     database = self.current_project_data['database']
    #     eps = self.eps_comb.currentText()
    #     shot = self.shot_list_btn.text()
    #     task_name = self.task_name_comb.currentText().encode('utf-8') if eps != 'Asset' else ''
    #     cg_id = self.task_data[task_name]['cg_id'] if eps != 'Asset' else ''
    #     task_id = cg_id.split(',')[2] if eps != 'Asset' else ''
    #     if eps != 'Asset':
    #         note = self.note_text.toPlainText().replace(' ', '_').replace(',', '_')
    #         if note:
    #             self.cmd_cgtw_note(database, task_id, note)


    def _check_mov_match(self):
        match = False
        # pipeline = self.pipeline_comb.currentText()
        # pipeline_name = self.pipeline_map[pipeline]  # self.pipeline_nas_map[pipeline]
        # shot_name = self.shot_list_btn.text()
        # task_name = self.task_name_comb.currentText()
        # eps = self.eps_comb.currentText()
        # cgtw_path = self.current_project_config.get('path', '')
        # mov = self.mov_list_comb.currentText()
        #
        # project = self.choose_project_btn.text()

        create_mov_path = self._get_mov_path()
        mov_name = os.path.split(create_mov_path)[1]
        mov = self.mov_list_comb.currentText()
        print("_check_mov_match:",mov_name,mov)
        print(type(mov_name),type(mov))
        if mov.encode('utf8') == mov_name.encode('utf8'):
            match = True
            # mov_name = os.path.split(mov)[0]
            # split_mov = mov_name.split('_')
            # mov_version = split_mov[-1]
            # if mov_version == version:
            #     match = True
        return match


    def _check_cgtw_exist(self):

        CanDo = False

        if self.check_mov.isChecked() and self.check_cgtw.isChecked(): # 当两者都提交时
            cgtw_mov = self._get_cgtw_mov_path()
            cgtw_submitFile_path = self._get_cgtw_submitFile_path()
            if not os.path.exists(cgtw_mov) and not os.path.exists(cgtw_submitFile_path):
                CanDo = True
        elif self.check_mov.isChecked():
            cgtw_mov = self._get_cgtw_mov_path()
            if not os.path.exists(cgtw_mov):
                CanDo = True
        elif self.check_cgtw.isChecked():
            cgtw_submitFile_path = self._get_cgtw_submitFile_path()
            if not os.path.exists(cgtw_submitFile_path):
                CanDo = True
        return CanDo

    def _sumbit(self):
        check = self._check_cgtw_exist()
        if not check:
            result = QMessageBox.question(self, u'提示', '当前提交文件已存在，是否覆盖', QMessageBox.Yes | QMessageBox.No,
                                          QMessageBox.No)  # 默认关闭界面选择No
            if result == QMessageBox.Yes:
                self.__submit()
            else:
                pass

        else:
            self.__submit()


    def __submit(self):
        self.text_brower.clear()
        stop = 0
        # to the daily
        if self.check_daily.isChecked():
            result = self._submit_daily()
            current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            self.text_brower.append(u'{}  :提交mov到daily {}\n'.format(current_time, result))

        # submit mov to cgtw
        if self.check_mov.isChecked():
            result = self._submit_mov()  # 已包含提交note
            current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
            self.text_brower.append(u'{}  :提交mov到cgtw {}\n'.format(current_time, result))
            if result == u'失败':
                stop = 1

        # pack to cgtw
        if self.check_cgtw.isChecked() and not stop:
            self.pack()

    def setWriteConfig(self,write, path, fps,start,end):
        write['file'].fromUserText(path)
        # write['meta_codec'].setValue('avc1')
        write['mov64_fps'].setValue(fps)
        write['meta_codec'].setValue('avc1')
        write['mov64_codec'].setValue('h264')
        write['first'].setValue(start)
        write['last'].setValue(end)


    def _get_mov_path(self):
        """
        获取配置后 自动生成的mov路径
        """
        nuke_dir = self.nuke_dir_edit.text()
        project = self.choose_project_btn.text()
        # eps = self.eps_comb.currentText()
        # eps = self.eps_comb.currentText()
        # pipeline_show = self.pipeline_comb.currentText()
        # # pipeline = self.pipeline_map[pipeline_show]
        shot = self.shot_list_btn.text()
        task_name = self.task_name_comb.currentText()
        version = self.version_comb.currentText()
        # mov_name = '{}_{}_{}_{}_{}.mov'.format(project, eps, shot, task_name, version)
        mov_name = '{}_{}_{}.mov'.format(shot, task_name, version)
        mov_path = os.path.join(nuke_dir,'mov',mov_name)
        return mov_path

    def _get_write_data(self,writer):
        """
        获取write的data数据
        """
        data = {}
        if writer:
            mov_path = writer['file'].value()
            mov_name = os.path.split(mov_path)[1] if mov_path else ''
            job_name = os.path.splitext(mov_name)[0] if mov_name else ''
            name = writer.name()
            start = writer['first'].value()
            end = writer['last'].value()
            data['job_name'] = job_name
            data['writer'] = name
            data['start'] = str(start)
            data['end'] = str(end)

        return data

    def get_current_write(self):
        current_write = -1
        fps = self.fps_edit.text()
        start = self.start_edit.text()
        start = start if start else '0'
        end = self.end_edit.text()
        end = end if end else '0'
        sn = nuke.selectedNodes()
        writes = []
        for i in sn:
            if i.Class() == 'Write':
                writes.append(i)
                write_name = i.name()
                self.write_data[write_name] = i
                print('has')
        if writes:  #当选择了多个write节点时
            if len(writes) == 1:  #当仅有一个输出节点时
                mov_path = self._get_mov_path()
                w = writes[0]
                w.setSelected(True)
                w.showControlPanel()
                # self.current_write = w
                current_write = w
                # w['meta_codec'].setValue('avc1')  #set H264
                self.setWriteConfig(w, mov_path, int(fps),int(float(start)),int(float(end)))
            else:
                self.writes_list_window = WriteNodeList()
                self.writes_list_window.nodename_Signal.connect(self._set_write)
                self.writes_list_window.init_items(writes)
                self.writes_list_window.show()

        else:  #当选择的节点中不存在Write节点时，全局查找Write节点
            print('find all nodes')
            allnode = nuke.allNodes()
            allWrites=[]
            for n in allnode:
                if n.Class() == 'Write':
                    allWrites.append(n)
                    write_name = n.name()
                    self.write_data[write_name] = n
            if allWrites:  #当全局存在write节点时
                current_write = 0 #表示没有选择
                self.writes_list_window = WriteNodeList()
                self.writes_list_window.nodename_Signal.connect(self._set_write)
                self.writes_list_window.init_items(allWrites)
                self.writes_list_window.show()

        return current_write


    def write_daily(self,path):
        # import nuke
        self.write_data.clear()
        fps=self.fps_edit.text()
        start=self.start_edit.text()
        start=start if start else '0'
        end=self.end_edit.text()
        end=end if end else '0'
        sn = nuke.selectedNodes()
        writes = []
        for i in sn:
            if i.Class() == 'Write':
                writes.append(i)
                write_name = i.name()
                self.write_data[write_name] = i
                print('has')
        if writes:  #ѡ��Ľڵ��в�ѯ
            if len(writes) == 1:
                w = writes[0]
                w.setSelected(True)
                w.showControlPanel()
                self.current_write=w
                w['meta_codec'].setValue('avc1')  #set H264
                self.setWriteConfig(w, path, int(fps),int(float(start)),int(float(end)))
            else:
                self.writes_list_window=WriteNodeList()
                self.writes_list_window.nodename_Signal.connect(self._set_write)
                self.writes_list_window.init_items(writes)
                self.writes_list_window.show()

        else:  #ѡ�еĽڵ���û��write����ô��ȫ�ֽڵ��в�ѯ
            print('find all nodes')
            allnode = nuke.allNodes()
            allWrites=[]
            for n in allnode:
                if n.Class() == 'Write':
                    allWrites.append(n)
                    write_name = n.name()
                    self.write_data[write_name] = n
            if allWrites:
                self.writes_list_window = WriteNodeList()
                self.writes_list_window.nodename_Signal.connect(self._set_write)
                self.writes_list_window.init_items(allWrites)
                self.writes_list_window.show()

    def _set_write_Ori(self,write_name):

        fps=self.fps_edit.text()
        start=self.start_edit.text()
        start=start if start else '0'
        end=self.end_edit.text()
        end=end if end else '0'
        w=self.write_data[write_name]
        w.setSelected(True)
        w.showControlPanel()
        self.current_write=w
        check_status=self.check_path_status()
        set_path=''
        if check_status>1:  #����ѡ����cgtw
            set_path=self.cgtw_path
        else:
            set_path=self.get_daily_mov_path()[0]
        w['meta_codec'].setValue('avc1')  #set H264
        self.setWriteConfig(w, set_path, int(fps),int(float(start)),int(float(end)))


    def _set_write(self,write_name):

        fps = self.fps_edit.text()
        start = self.start_edit.text()
        start = start if start else '0'
        end = self.end_edit.text()
        end = end if end else '0'
        w = self.write_data[write_name]
        w.setSelected(True)
        w.showControlPanel()
        self.current_write = w
        # check_status=self.check_path_status()
        # set_path=''
        # if check_status>1:  #����ѡ����cgtw
        #     set_path=self.cgtw_path
        # else:
        #     set_path=self.get_daily_mov_path()[0]
        mov_path = self._get_mov_path()
        # w['meta_codec'].setValue('avc1')  #set H264
        self.setWriteConfig(w, mov_path,int(fps),int(float(start)),int(float(end)))


    def getWeekNum(self,date):
        """
        �������ڷ��أ�������������һ�ܵ����λ��
        :param date: 2020-08-13 ���ָ�ʽ
        :return:
        """
        str_year, str_month, str_day = date.split('-')
        weeknum = datetime.datetime(int(str_year), int(str_month), int(str_day)).strftime('%w')
        return int(weeknum)

    def delta_date(self,start_date, end_date):
        """
        ������ʼ��������ڳ���
        :param start_date:
        :param end_date:
        :return:
        """
        start = datetime.datetime.strptime(start_date, "%Y-%m-%d")
        end = datetime.datetime.strptime(end_date, "%Y-%m-%d")
        delta_day = (end - start).days
        return delta_day

    def dateAdd(self,start_date, days):
        """
        ����ȷ�����ڼӷ�
        :param start_date:
        :param days:
        :return:
        """
        d = datetime.datetime.strptime(start_date, '%Y-%m-%d')
        delta = datetime.timedelta(days=days)
        n_days = d + delta
        return (n_days.strftime('%Y-%m-%d'))

    def getWeekdayNum(self, int_year, int_month, int_day):
        '''
        ��ȡ���ڼ�
        :return:
        '''
        # ���ǻ�ȡ��ǰ����

        weekday = datetime.datetime(int_year, int_month, int_day).strftime("%w")
        # print(weekday)
        return int(weekday)


    def getNearWeekNum(self,num):
        near_num = 0
        if num <= 2:
            near_num = 2
        elif num <= 4:
            near_num = 4
        elif num <= 6:
            near_num = 6
        return near_num


    def get_date(self,pipeline):
        """
        for dailies date direction
        :param pipeline:
        :return:
        """
        today = time.strftime("%Y-%m-%d")

        # if pipeline.startswith('FX'):  #
        #     apm=time.strftime('%p')
        #     return today,apm
        if pipeline.startswith('Env'):
            today_week_num = self.getWeekNum(today)
            # print('today_week_num:', today_week_num)
            near_num = self.getNearWeekNum(today_week_num)
            # print('near_num:', near_num)
            delta = near_num - today_week_num
            last_date = self.dateAdd(today, delta)
            # print(last_date)
            return last_date,''
        else:
            apm=time.strftime('%p')
            return today,apm

    def closeEvent(self, *args, **kwargs):

        self.setHidden(True)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    # path=r'\\192.168.100.30\ZZ_project'
    # path = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'Control')
    g = ExportMov()
    # g=ProjectList()
    data={'MZDYY':{'database': 'proj_mzdyy', 'entity_name': 'MZDYY', 'full_name': '��֭������'},'AAA':{'database': 'proj_mzdyy', 'entity_name': 'MZDYY', 'full_name': '��֭������'}}
    # g.set_data(data)
    # g=ShotListWindow()
    # g.set_data(data)
    g.show()
    sys.exit(app.exec_())
